package com.clkj.xiuzheng.pojo.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.cert.CertificatesManager;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.util.Objects;

/**
 * @author yawang
 * @create 2024/06/25 10:22:06
 **/
public class OrderReturnUtil {
    private static final Logger log = LoggerFactory.getLogger(OrderReturnUtil.class);
    private static final com.alibaba.fastjson.JSON JSON =null ;

    public static JSONObject refundOrder(String orderNumber, String returnNumber, String oldMoney, String returnMoney) throws Exception {
        // 配置参数
        JSONObject requestParam = new JSONObject();
        // 商户订单号 orderId
        requestParam.put("out_trade_no", orderNumber);
        // 商户退款单号
        requestParam.put("out_refund_no", returnNumber);
        // 退款回调地址
        requestParam.put("notify_url", "https://www.ccclkj.cn:2036/order/returnPay");
        // 金额信息 amount (单位都是分)
        JSONObject amount = new JSONObject();
        // 原订单金额 total
        amount.put("total", oldMoney);
        // 退款金额 refund
        amount.put("refund", returnMoney);
        // 退款币种 CNY 人民币
        amount.put("currency","CNY");
        // 金额信息 amount: 原订单金额 total 退款金额 refund (单位都是分)
        requestParam.put("amount", amount);

        try {
            // 调用请求接口
            JSONObject jsonObject = getBodyAsJsonByPost("https://api.mch.weixin.qq.com/v3/refund/domestic/refund",
                    requestParam);
            // 异常情况
            if (Objects.nonNull(jsonObject.get("code"))) {
                throw new Exception(jsonObject.get("message").toString());
            }
            log.info("微信申请退款返回结果" + "response:" + jsonObject);
            return jsonObject;
        } catch (Exception e) {
            log.info("微信退款" + returnNumber + "失败");
            e.printStackTrace();
            throw new Exception("退款失败:" + e.getMessage());
        }
    }













        /**
         * 调用微信支付 post请求 统一配置
         * 要微信签名认证
         *
         * @param url          请求url
         * @param requestParam 请求参数
         * @return JSONObject
         */
        public static JSONObject getBodyAsJsonByPost(String url, JSONObject requestParam) throws Exception {
            // 1.设置请求url和请求头
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader(WechatPayHttpHeaders.ACCEPT, WechatPayHttpHeaders.APPLICATION_JSON);
            httpPost.addHeader(WechatPayHttpHeaders.CONTENT_TYPE, WechatPayHttpHeaders.APPLICATION_JSON_UTF);

            // 2.传入参数
            String jsonString = JSON.toJSONString(requestParam);
            httpPost.setEntity(new StringEntity(jsonString, StandardCharsets.UTF_8));

            // 3.调用接口 获取预支付交易会话标识 prepay_id
            CloseableHttpResponse response =getHttpClient(getVerifier()).execute(httpPost);

            // 4.获取返回值 转为JSON
            String bodyAsString = EntityUtils.toString(response.getEntity());
            return JSON.parseObject(bodyAsString);
        }

    /**
     * 构造HttpClient 实现 微信申请接口 调用功能
     *
     * @param verifier 微信验签器
     * @return CloseableHttpClient
     */
    public static CloseableHttpClient getHttpClient( Verifier verifier) {
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(WxApi.partnerkey.getBytes(StandardCharsets.UTF_8)));
        // 通过WechatPayHttpClientBuilder构造的HttpClient，会自动的处理签名和验签
        WechatPayHttpClientBuilder builder = WechatPayHttpClientBuilder.create()
                .withMerchant(WxApi.getMchId(), WxApi.wechatPayserialNo, merchantPrivateKey)
                .withValidator(new WechatPay2Validator(verifier));
        return builder.build();
    }
    /**
     * 获取验证功能
     *
     * @return Verifier 微信验签器
     */
    public static Verifier getVerifier() throws Exception {
        try {
            PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(WxApi.partnerkey.getBytes(StandardCharsets.UTF_8)));
            // 定时更新平台证书功能
            // 获取证书管理器实例
            CertificatesManager certificatesManager = CertificatesManager.getInstance();
            // 向证书管理器增加需要自动更新平台证书的商户信息
            certificatesManager.putMerchant(WxApi.getMchId(), new WechatPay2Credentials(WxApi.getMchId(),
                    new PrivateKeySigner(WxApi.wechatPayserialNo, merchantPrivateKey)), WxApi.partnerkey.getBytes(StandardCharsets.UTF_8));
            // 从证书管理器中获取verifier=>验签器
            return certificatesManager.getVerifier(WxApi.getMchId());
        } catch (Exception e) {
            log.warn("验证出错");
            throw new Exception("微信证书出错 联系客服");
        }
    }





}
